<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Payment Handler API</h1>
        <p class="text-gray-300 text-lg">
          创建自定义支付方式，与 Payment Request API 集成
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300 mb-4">
          您的浏览器不支持 Payment Handler API。此功能需要 Chrome 68+ 或其他支持该 API 的浏览器。
        </p>
        <p class="text-gray-400 text-sm">
          注意：Payment Handler API 需要 HTTPS 环境和 Service Worker 支持。
        </p>
      </div>

      <!-- Service Worker 状态 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">Service Worker 状态</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-400 text-sm mb-2">注册状态</div>
              <div class="text-white text-xl font-semibold">
                {{ swState }}
              </div>
            </div>
            <i
              :class="swRegistered ? 'i-carbon-checkmark-filled text-green-400' : 'i-carbon-warning-filled text-yellow-400'"
              class="text-4xl"
            ></i>
          </div>
        </div>

        <div class="flex gap-3">
          <button
            @click="registerServiceWorker"
            :disabled="swRegistered"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-cloud-service-management mr-2"></i>
            {{ swRegistered ? 'Service Worker 已注册' : '注册 Service Worker' }}
          </button>
          
          <button
            v-if="swRegistered"
            @click="unregisterServiceWorker"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-close mr-2"></i>
            注销 Service Worker
          </button>
        </div>
      </div>

      <!-- 支付方式管理 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">支付方式管理</h2>
        
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <!-- 添加支付方式 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-white font-semibold mb-4">注册支付方式</h3>
            
            <div class="space-y-4">
              <div>
                <label class="text-white font-medium mb-2 block">支付方式标识符</label>
                <input
                  v-model="newPaymentMethod.id"
                  type="text"
                  placeholder="例如: https://example.com/pay"
                  class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
                >
              </div>

              <div>
                <label class="text-white font-medium mb-2 block">显示名称</label>
                <input
                  v-model="newPaymentMethod.name"
                  type="text"
                  placeholder="例如: 我的支付方式"
                  class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
                >
              </div>

              <div>
                <label class="text-white font-medium mb-2 block">图标 URL (可选)</label>
                <input
                  v-model="newPaymentMethod.icon"
                  type="text"
                  placeholder="https://example.com/icon.png"
                  class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
                >
              </div>

              <button
                @click="registerPaymentMethod"
                :disabled="!swRegistered || !newPaymentMethod.id || !newPaymentMethod.name"
                class="tech-button w-full disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="i-carbon-add mr-2"></i>
                注册支付方式
              </button>
            </div>
          </div>

          <!-- 已注册的支付方式 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-white font-semibold mb-4">已注册的支付方式</h3>
            
            <div v-if="paymentMethods.length === 0" class="text-gray-400 text-center py-8">
              <i class="i-carbon-wallet text-4xl mb-2 block mx-auto"></i>
              <p>暂无已注册的支付方式</p>
            </div>

            <div v-else class="space-y-3">
              <div
                v-for="(method, index) in paymentMethods"
                :key="index"
                class="bg-gray-700 rounded-lg p-4 flex items-center justify-between"
              >
                <div class="flex items-center">
                  <i class="i-carbon-payment text-2xl text-tech-accent mr-3"></i>
                  <div>
                    <div class="text-white font-medium">{{ method.name }}</div>
                    <div class="text-gray-400 text-sm">{{ method.id }}</div>
                  </div>
                </div>
                <button
                  @click="unregisterPaymentMethod(method.id)"
                  class="text-red-400 hover:text-red-300"
                  title="删除"
                >
                  <i class="i-carbon-trash-can text-xl"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付请求测试 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">支付请求测试</h2>
        <p class="text-gray-300 mb-6">
          使用 Payment Request API 测试已注册的支付方式
        </p>

        <!-- 商品信息 -->
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <h3 class="text-white font-semibold mb-4">商品信息</h3>
          
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="text-white font-medium mb-2 block">商品名称</label>
              <input
                v-model="paymentDetails.label"
                type="text"
                class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">金额</label>
              <input
                v-model.number="paymentDetails.amount"
                type="number"
                min="0"
                step="0.01"
                class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">货币</label>
              <select
                v-model="paymentDetails.currency"
                class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
              >
                <option value="CNY">CNY (人民币)</option>
                <option value="USD">USD (美元)</option>
                <option value="EUR">EUR (欧元)</option>
                <option value="JPY">JPY (日元)</option>
              </select>
            </div>
          </div>
        </div>

        <button
          @click="testPaymentRequest"
          :disabled="!swRegistered || paymentMethods.length === 0 || isProcessing"
          class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <i class="i-carbon-purchase mr-2"></i>
          {{ isProcessing ? '处理中...' : '发起支付请求' }}
        </button>
      </div>

      <!-- 支付结果 -->
      <div v-if="paymentResult" class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">支付结果</h2>
        
        <div
          class="bg-gray-800 rounded-lg p-6"
          :class="paymentResult.success ? 'border-l-4 border-green-400' : 'border-l-4 border-red-400'"
        >
          <div class="flex items-center mb-4">
            <i
              :class="paymentResult.success ? 'i-carbon-checkmark-filled text-green-400' : 'i-carbon-close-filled text-red-400'"
              class="text-3xl mr-3"
            ></i>
            <div>
              <div class="text-white text-xl font-semibold">
                {{ paymentResult.success ? '支付成功' : '支付失败' }}
              </div>
              <div class="text-gray-400 text-sm">
                {{ paymentResult.timestamp }}
              </div>
            </div>
          </div>

          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-400">支付方式:</span>
              <span class="text-white">{{ paymentResult.methodName }}</span>
            </div>
            <div v-if="paymentResult.details" class="pt-3 border-t border-gray-700">
              <div class="text-gray-400 mb-2">详细信息:</div>
              <pre class="text-xs text-gray-300 bg-gray-900 p-3 rounded overflow-x-auto">{{ JSON.stringify(paymentResult.details, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作日志 -->
      <div v-if="logs.length > 0" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">操作日志</h2>
          <button
            @click="clearLogs"
            class="text-red-400 hover:text-red-300 text-sm"
          >
            <i class="i-carbon-clean mr-1"></i>
            清空日志
          </button>
        </div>

        <div class="space-y-2 max-h-64 overflow-y-auto">
          <div
            v-for="(log, index) in logs.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 flex items-start text-sm"
          >
            <i
              :class="getLogIcon(log.type)"
              class="text-lg mr-3 mt-0.5"
            ></i>
            <div class="flex-1">
              <div class="text-white">{{ log.message }}</div>
              <div class="text-gray-400 text-xs mt-1">{{ log.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 68+ (需要 HTTPS 环境和 Service Worker)</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要接口</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">PaymentManager</code> - 管理支付方式</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">PaymentInstruments</code> - 支付工具集合</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">canMakePayment()</code> - 检查支付可用性</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">paymentrequest</code> - 支付请求事件</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">工作流程</h4>
            <ol class="list-decimal list-inside space-y-1 text-sm">
              <li>注册 Service Worker</li>
              <li>在 Service Worker 中注册支付方式</li>
              <li>商家网站使用 Payment Request API 发起支付</li>
              <li>浏览器显示支付界面，包含自定义支付方式</li>
              <li>用户选择支付方式</li>
              <li>触发 Service Worker 的 paymentrequest 事件</li>
              <li>处理支付并返回结果</li>
            </ol>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>集成第三方支付服务（支付宝、微信支付等）</li>
              <li>创建自定义支付流程</li>
              <li>企业内部支付系统</li>
              <li>加密货币钱包集成</li>
              <li>银行应用集成</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">安全要求</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>必须在 HTTPS 环境下运行</li>
              <li>需要用户主动授权</li>
              <li>支付方式标识符必须使用安全的 URL</li>
              <li>敏感数据应加密传输</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">与 Payment Request API 的关系</h4>
            <p class="text-sm leading-relaxed">
              Payment Handler API 扩展了 Payment Request API 的功能。
              Payment Request API 提供了统一的支付界面，
              而 Payment Handler API 允许开发者创建自定义的支付方式处理器。
              两者配合使用，可以实现完整的 Web 支付解决方案。
            </p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">注意事项</h4>
            <ul class="list-disc list-inside space-y-1 text-sm text-yellow-400">
              <li>⚠️ 这是一个较新的 API，浏览器支持有限</li>
              <li>⚠️ 需要在实际的 HTTPS 服务器上测试（localhost 除外）</li>
              <li>⚠️ 本演示仅展示 API 使用方法，不包含实际支付处理</li>
              <li>⚠️ 生产环境需要处理安全验证和错误处理</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 类型定义
interface PaymentMethod {
  id: string
  name: string
  icon?: string
}

interface Log {
  type: 'info' | 'success' | 'warning' | 'error'
  message: string
  timestamp: string
}

interface PaymentResult {
  success: boolean
  methodName: string
  details?: any
  timestamp: string
}

// 响应式状态
const isSupported = ref(
  'serviceWorker' in navigator && 'PaymentRequest' in window
)
const swRegistered = ref(false)
const swState = ref('未注册')
const isProcessing = ref(false)

const paymentMethods = ref<PaymentMethod[]>([])
const logs = ref<Log[]>([])
const paymentResult = ref<PaymentResult | null>(null)

// 新支付方式
const newPaymentMethod = ref<PaymentMethod>({
  id: 'https://example.com/pay',
  name: '示例支付方式',
  icon: ''
})

// 支付详情
const paymentDetails = ref({
  label: '示例商品',
  amount: 99.99,
  currency: 'CNY'
})

// 初始化
onMounted(() => {
  checkServiceWorker()
})

// 检查 Service Worker 状态
const checkServiceWorker = async () => {
  if (!('serviceWorker' in navigator)) return

  try {
    const registration = await navigator.serviceWorker.getRegistration()
    if (registration) {
      swRegistered.value = true
      swState.value = '已注册'
      addLog('success', 'Service Worker 已注册')
    } else {
      swState.value = '未注册'
    }
  } catch (err) {
    console.error('检查 Service Worker 失败:', err)
  }
}

// 注册 Service Worker
const registerServiceWorker = async () => {
  if (!('serviceWorker' in navigator)) {
    addLog('error', '浏览器不支持 Service Worker')
    return
  }

  try {
    addLog('info', '正在注册 Service Worker...')

    // 创建一个简单的 Service Worker
    const swCode = `
      self.addEventListener('install', (event) => {
        console.log('Service Worker 安装中...');
        self.skipWaiting();
      });

      self.addEventListener('activate', (event) => {
        console.log('Service Worker 已激活');
        event.waitUntil(clients.claim());
      });

      self.addEventListener('paymentrequest', (event) => {
        console.log('收到支付请求:', event);
        
        event.respondWith(new Promise((resolve) => {
          // 这里应该打开支付界面并处理支付
          // 本演示直接返回模拟结果
          resolve({
            methodName: event.methodData[0].supportedMethods,
            details: {
              status: 'success',
              transactionId: 'mock-' + Date.now()
            }
          });
        }));
      });
    `

    const blob = new Blob([swCode], { type: 'application/javascript' })
    const swUrl = URL.createObjectURL(blob)

    const registration = await navigator.serviceWorker.register(swUrl)
    
    await navigator.serviceWorker.ready
    
    swRegistered.value = true
    swState.value = '已注册'
    addLog('success', 'Service Worker 注册成功')

    URL.revokeObjectURL(swUrl)

  } catch (err) {
    console.error('注册 Service Worker 失败:', err)
    addLog('error', `Service Worker 注册失败: ${err instanceof Error ? err.message : '未知错误'}`)
  }
}

// 注销 Service Worker
const unregisterServiceWorker = async () => {
  try {
    const registration = await navigator.serviceWorker.getRegistration()
    if (registration) {
      await registration.unregister()
      swRegistered.value = false
      swState.value = '未注册'
      paymentMethods.value = []
      addLog('success', 'Service Worker 已注销')
    }
  } catch (err) {
    console.error('注销 Service Worker 失败:', err)
    addLog('error', '注销失败')
  }
}

// 注册支付方式
const registerPaymentMethod = async () => {
  if (!swRegistered.value) {
    addLog('error', '请先注册 Service Worker')
    return
  }

  try {
    addLog('info', `正在注册支付方式: ${newPaymentMethod.value.name}`)

    // 检查是否已存在
    if (paymentMethods.value.some(m => m.id === newPaymentMethod.value.id)) {
      addLog('warning', '该支付方式已注册')
      return
    }

    // 添加到列表
    paymentMethods.value.push({ ...newPaymentMethod.value })
    
    addLog('success', `支付方式 "${newPaymentMethod.value.name}" 注册成功`)

    // 重置表单
    newPaymentMethod.value = {
      id: 'https://example.com/pay',
      name: '示例支付方式',
      icon: ''
    }

  } catch (err) {
    console.error('注册支付方式失败:', err)
    addLog('error', `注册失败: ${err instanceof Error ? err.message : '未知错误'}`)
  }
}

// 注销支付方式
const unregisterPaymentMethod = (id: string) => {
  const method = paymentMethods.value.find(m => m.id === id)
  if (method) {
    paymentMethods.value = paymentMethods.value.filter(m => m.id !== id)
    addLog('success', `支付方式 "${method.name}" 已删除`)
  }
}

// 测试支付请求
const testPaymentRequest = async () => {
  if (!swRegistered.value || paymentMethods.value.length === 0) {
    addLog('error', '请先注册 Service Worker 和支付方式')
    return
  }

  isProcessing.value = true
  paymentResult.value = null

  try {
    addLog('info', '发起支付请求...')

    // 构建支付方式数据
    const methodData = paymentMethods.value.map(method => ({
      supportedMethods: method.id,
      data: {}
    }))

    // 构建支付详情
    const details = {
      total: {
        label: paymentDetails.value.label,
        amount: {
          currency: paymentDetails.value.currency,
          value: paymentDetails.value.amount.toString()
        }
      }
    }

    // 创建支付请求
    const request = new PaymentRequest(methodData, details)

    // 检查是否可以支付
    const canMakePayment = await request.canMakePayment()
    
    if (!canMakePayment) {
      addLog('warning', '无法使用已注册的支付方式')
      paymentResult.value = {
        success: false,
        methodName: '无',
        timestamp: new Date().toLocaleString('zh-CN')
      }
      return
    }

    addLog('info', '显示支付界面...')

    // 显示支付界面
    const response = await request.show()

    // 完成支付
    await response.complete('success')

    paymentResult.value = {
      success: true,
      methodName: response.methodName,
      details: response.details,
      timestamp: new Date().toLocaleString('zh-CN')
    }

    addLog('success', '支付完成')

  } catch (err) {
    console.error('支付请求失败:', err)
    
    if (err instanceof Error) {
      if (err.name === 'AbortError') {
        addLog('warning', '用户取消了支付')
      } else {
        addLog('error', `支付失败: ${err.message}`)
      }
    } else {
      addLog('error', '支付失败')
    }

    paymentResult.value = {
      success: false,
      methodName: '无',
      timestamp: new Date().toLocaleString('zh-CN')
    }

  } finally {
    isProcessing.value = false
  }
}

// 添加日志
const addLog = (type: 'info' | 'success' | 'warning' | 'error', message: string) => {
  logs.value.push({
    type,
    message,
    timestamp: new Date().toLocaleTimeString('zh-CN')
  })

  // 只保留最近 50 条
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 获取日志图标
const getLogIcon = (type: string) => {
  const icons = {
    info: 'i-carbon-information-filled text-blue-400',
    success: 'i-carbon-checkmark-filled text-green-400',
    warning: 'i-carbon-warning-filled text-yellow-400',
    error: 'i-carbon-error-filled text-red-400'
  }
  return icons[type as keyof typeof icons]
}
</script>

